/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package readxml;

/**
 *
 * @author SONGOKU20
 */
import java.io.*;
import java.util.Scanner;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
public class ReadXML{
    public static void main(String[] args) {
        try {
            Scanner input=new Scanner(System.in);
            System.out.println("Nhap vao file can doc: ");
            String fileName=input.nextLine();
            File xmlFile = new File(fileName);
            DocumentBuilder dBuilder;
            dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = dBuilder.parse(xmlFile);
            System.out.println("Root element : " + doc.getDocumentElement().getNodeName());
            //Doc va in ra gia tri cua cac node
            if (doc.hasChildNodes()) {
                printNote(doc.getChildNodes());
            }
            System.out.println("End Root element: " + doc.getDocumentElement().getNodeName());
        } catch (ParserConfigurationException | SAXException | IOException e) {
        }
    }
    private static void printNote(NodeList nodeList) {
        for (int count = 0; count < nodeList.getLength(); count++) {
            Node tempNode = nodeList.item(count);
            if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
                /*
                 * Ten cua Node mo tab tempNode.getNodeName() + " [OPEN]");
                 * Gia tri cua node mo tab "Node Value = " + tempNode.getTextContent());
                */
                tempNode.getNodeName();
                System.out.print(tempNode.getTextContent());
                if (tempNode.hasAttributes()) {
                    NamedNodeMap nodeMap = tempNode.getAttributes();
                    for (int i = 0; i < nodeMap.getLength(); i++) {
                        /*In ra ten cua attributes: node.getNodeName()
                         * In ra gia tri cua attributes: node.getNodeValue()
                         */
                        Node node = nodeMap.item(i);
                        node.getNodeName();
                        System.out.print(node.getNodeValue());
                    }
                }
                    /*
                     * lap lai lan nua neu nhu tim thay node con
                     * if (tempNode.hasChildNodes()) {
                     * De quy node con printNote(tempNode.getChildNodes());
                     * In ra ten cua nut tab dong: tempNode.getNodeName()
                     * }
                     */
                tempNode.getNodeName();//Lay ten cua node dong tab
            }
        }
    }
}
